// @algorithm @lc id=124 lang=cpp 
// @title binary-tree-maximum-path-sum


// @test([1,2,3])=6
// @test([-10,9,20,null,null,15,7])=42
// @test([2,-1])=2
class Solution {
public:
    int maxPathSum(TreeNode* root) {
        int ans = INT_MIN;
        function<int(TreeNode*)> traverse = [&](TreeNode* tree)->int{
            if(!tree) return 0;
            auto left = max(0, traverse(tree->left)),
                right = max(0, traverse(tree->right));
            ans = max(ans, tree->val + left + right);
            return tree->val + max(left, right);
        };
        traverse(root);
        return ans;
    }
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */